package com.fengye.middleware.rabbitmq.boot.dead.letter;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * @author sky
 * @date 2021年06月10日 10:44 上午
 */
@Component
@Slf4j
public class DeadPublisher {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Value("${mq.producer.basic.exchange.name}")
    private String basicProducerExchangeName;

    @Value("${mq.producer.basic.routing.key.name}")
    private String basicProducerRoutingKeyName;

    public void sendMsg(DeadLetterInfo info) {
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        rabbitTemplate.setExchange(basicProducerExchangeName);
        rabbitTemplate.setRoutingKey(basicProducerRoutingKeyName);

        try {
            rabbitTemplate.convertAndSend(info, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    // 获取消息属性对象
                    MessageProperties messageProperties = message.getMessageProperties();

                    // 设置 header，接收时可以直接用对象进行接收
                    messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, DeadLetterInfo.class);

                    // 设置消息的持久化策略
                    messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);

                    // 设置消息的 TTL。当消息和队列都设置了 TTL 时，取较短时间的值
                    // messageProperties.setExpiration(String.valueOf(10000));
                    return message;
                }
            });

            log.info("死信队列 发送对象类型的消息进入死信队列，内容为 {}", info);
        } catch (Exception e) {
            log.error("死信队列 发送对象类型的消息进入死信队列出错", e.fillInStackTrace());
        }

    }
}
